package com.sinog.front.controller.biz;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinog.core.model.NoticeInfo;
import com.sinog.core.model.UploadAppendixFile;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.MapUtil;
import com.sinog.core.util.PageReturnUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.log.Log;
import com.sinog.front.feign.biz.FtpUtilService;
import com.sinog.front.feign.biz.NoticeInfoManageService;
import com.sinog.front.service.azbj.uploadappendix.UploadAppendixFileService;
import com.sinog.front.service.user.UserFacade;
import com.sinog.front.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - NoticeInfoManageController
 * @author zhangcb
 * @date 2020年2月16日 18点48分
 */
@Slf4j
@RestController
public class NoticeInfoManageController {

    @Resource
    private NoticeInfoManageService noticeInfoManageService;
    @Resource
    private UploadAppendixFileService uploadAppendixFileService;
    @Autowired
    private UserFacade userService;
    @Autowired
    private FtpUtilService ftpUtilService;

    /**
     * 获取首页通知公告列表
     * @return Map<String,Object>
     */
    @GetMapping("/basic/tzgg/getSyTzggList")
    public Map<String,Object> getSyTzggList() {
        UserDTO userDTO = userService.getAuthentication();
        String level = userDTO.getLevel();
        if(StringUtils.isNotBlank(level) && Constants.Number.NUM_TWO <= level.length() && Constants.CharFinal.CHAR_ZERO == level.charAt(0)) {
            level = level.substring(1);
        }
        List<HashMap<String,Object>> resultList = noticeInfoManageService.getSyTzggList(userDTO.getDepartid(),userDTO.getAccount(),level);
        List<Map<String,Object>> returnList = new ArrayList<>(16);
        Map<String,Object> resmap = new HashMap<>(16);
        for(HashMap<String,Object> stringObjectHashMap : resultList) {
            Map<String,Object> resultMap = new HashMap<>(16);
            //编号
            String id = stringObjectHashMap.get("id").toString();
            //编号
            resultMap.put("id",id);
            //todo 测试
            MapUtil.setValueMapToMap(stringObjectHashMap,resultMap,"title","fbdw","adddate","enddate","titlecolor","type");
            int count = Integer.parseInt(stringObjectHashMap.get("new").toString());
            if(Constants.Number.NUM_ZERO != count) {
                //是否被查看
                resultMap.put("new",Constants.NumberStr.NUM_STR_ONE);
            } else {
                //是否被查看
                resultMap.put("new",Constants.NumberStr.NUM_STR_TWO);
            }
            try {
                NoticeInfo noticeInfo = noticeInfoManageService.findTzggById(id);
                if(null == noticeInfo) {
                    resultMap.put("content","");
                } else {
                    String content = noticeInfo.getContent();
                    resultMap.put("content",content);
                }
                returnList.add(resultMap);
            } catch(RuntimeException e) {
                log.error("发生异常:{}",e.getMessage());
            }
        }
        resmap.put("error",Constants.Number.NUM_ZERO);
        resmap.put("data",returnList);
        resmap.put("msg","success");
        return resmap;
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - 列表
     * @param request request
     * @param searchKey searchKey
     * @param startDate startDate
     * @param endDate endDate
     * @param effective effective
     * @return String
     */
    @GetMapping("/azbj/tzgggl/getNoticeInfoList")
    public String gettNoticeInfoList(HttpServletRequest request,
                                     @RequestParam(required = false, defaultValue = "-1") String searchKey,
                                     @RequestParam(required = false, defaultValue = "-1") String startDate,
                                     @RequestParam(required = false, defaultValue = "-1") String endDate,
                                     @RequestParam(required = false, defaultValue = "-1") String effective) {
        UserDTO userDTO = userService.getAuthentication();
        Integer pageIndex = Integer.valueOf(request.getParameter("pageIndex"));
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
        Page<Map<String,String>> page = noticeInfoManageService.getNoticeInfoList(searchKey,userDTO.getDepartid(),startDate,endDate,
                                                                                    effective,userDTO.getAccount(),pageIndex,pageSize,userDTO.getLevel());
        for(int i = 0; i < page.getRecords().size(); i++) {
            Map<String,String> resultMap = page.getRecords().get(i);
            String id = resultMap.get("id");
            try {
                NoticeInfo noticeInfo = noticeInfoManageService.findTzggById(id);
                if(ObjectUtils.isNotEmpty(noticeInfo)) {
                    resultMap.put("content",noticeInfo.getContent());
                    page.getRecords().set(i,resultMap);
                }
            } catch(RuntimeException e) {
                log.error("发生异常:{}",e.getMessage());
            }
        }
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - （新增/更新）
     * @param request request
     * @param data data
     * @return Result
     */
    @Log(type = "新增", value = "保存通知公告信息（新增/更新）")
    @PostMapping("/azbj/tzgggl/noticeInfoManage/save")
    public Result reportInfoManage(HttpServletRequest request,String data) {
        boolean tag = noticeInfoManageService.save(data);
        if(tag) {
            return Result.success("保存成功");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - 删除
     * @param request request
     * @param id id
     * @return Result
     */
    @Log(type = "删除", value = "删除公告")
    @DeleteMapping("/azbj/tzgggl/noticeInfoManage/delete/{id}")
    public Result noticeInfoManageDel(HttpServletRequest request,@PathVariable String id) {
        try {
            //删除政策文件表
            boolean result = noticeInfoManageService.deleteNoticeInfo(id);
            //存在附件，删除附件文件
            boolean deletefileResult = true;
            //存在附件，删除附件表信息
            boolean fjresult = true;
            List<UploadAppendixFile> uploadAppendixFiles = noticeInfoManageService.getFilesListdata(id);
            if(CollectionUtils.isNotEmpty(uploadAppendixFiles)) {
                for(UploadAppendixFile uploadAppendixFile : uploadAppendixFiles) {
                    String path = FileUtil.getUploadFilePath();
                    File file = new File(path + uploadAppendixFile.getFileUrl());
                    if(file.exists()) {
                        deletefileResult = file.delete();
                    }
                }
                //删除附件表
                int fjdelete = noticeInfoManageService.deleteFjByid(id);
                if(uploadAppendixFiles.size() != fjdelete) {
                    fjresult = false;
                }
            }
            if(result && fjresult && deletefileResult) {
                return Result.success("删除成功！");
            }
        } catch(RuntimeException e) {
            log.error("发生异常:{}",e.getMessage());
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - 判断用户是否相同
     * @param user user
     * @return Result
     */
    @Log(ignore = true)
    @RequestMapping("/azbj/tzgggl/noticeInfoManage/identical/{user}")
    public Result identical(@PathVariable String user) {
        String edituser = userService.getAuthentication().getAccount();
        if(user.equals(edituser)) {
            return Result.success();
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - 获取有效期需要的下拉框数据
     * @param codeType codeType
     * @return List<Map < String,Object>>
     */
    @RequestMapping("/azbj/tzgggl/noticeInfo/getnoticeType")
    public List<Map<String,Object>> getNoticeType(String codeType) {
        return noticeInfoManageService.getNoticeType(codeType);
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - 下载时判断是否存在附件
     * @param request request
     * @param id id
     * @return Result
     */
    @RequestMapping("/azbj/tzgggl/noticeInfoManage/ifFileExist")
    public Result ifFileExist(HttpServletRequest request,String id) {
        int num;
        //根据列表id查询附件list数据
        List<UploadAppendixFile> fileslist = noticeInfoManageService.getFilesListdata(id);
        log.error("下载省级文件数量{}",fileslist.size());
        if(!fileslist.isEmpty()) {
            for(UploadAppendixFile uploadAppendixFile : fileslist) {
                num = ftpUtilService.fileIsExistence(uploadAppendixFile,Constants.NumberStr.NUM_STR_ONE);
                //找到文件则退出循环
                //只要有一个文件存在就让下载
                if(Constants.Number.NUM_ZERO < num) {
                    return Result.success();
                } else {
                    return Result.failure(ReturnCode.FAILURE);
                }
            }
        }
        //部级同步数据时省级不存在附件信息
        List<UploadAppendixFile> buFilesList = noticeInfoManageService.ifBujiFileExist(id);
        log.error("下载部级文件数量{}",buFilesList.size());
        if(!buFilesList.isEmpty()) {
            for(UploadAppendixFile uploadAppendixFile : buFilesList) {
                num = ftpUtilService.fileIsExistence(uploadAppendixFile,Constants.NumberStr.NUM_STR_TWO);
                //找到文件则退出循环
                //只要有一个文件存在就让下载
                if(Constants.Number.NUM_ZERO < num) {
                    return Result.success();
                } else {
                    return Result.failure(ReturnCode.FAILURE);
                }
            }
        }
        return Result.failure(ReturnCode.FAILURE);
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - 通知公告下载附件
     * @param resp resp
     * @param request request
     * @param id id
     */
    @RequestMapping("/azbj/tzgggl/noticeInfoManage/downloadFilesZip/{id}")
    public void downloadFilesZip(HttpServletResponse resp,HttpServletRequest request,@PathVariable String id) {
        //根据列表id查询附件list数据
        List<UploadAppendixFile> uploadAppendixFiles = noticeInfoManageService.getFilesListdata(id);
        if(!CollectionUtils.isEmpty(uploadAppendixFiles)) {
            if(1 < uploadAppendixFiles.size()) {
                uploadAppendixFileService.downloadAppendixAllFile(resp,request,uploadAppendixFiles,Constants.NumberStr.NUM_STR_ONE);
            } else {
                uploadAppendixFileService.downloadAppendixFile(request,resp,uploadAppendixFiles.get(0)
                                                                                               .getFileUrl(),Constants.NumberStr.NUM_STR_ONE);
            }
            return;
        }
        //部级需要查找附件信息
        List<UploadAppendixFile> appendixFiles = noticeInfoManageService.ifBujiFileExist(id);
        log.info("下载部级下发的通知公告:{}",appendixFiles);
        if(!CollectionUtils.isEmpty(appendixFiles)) {
            if(1 < uploadAppendixFiles.size()) {
                log.info("下载多个文件:{}",appendixFiles.size());
                uploadAppendixFileService.downloadAppendixAllFile(resp,request,appendixFiles,Constants.NumberStr.NUM_STR_TWO);
            } else {
                log.info("下载单个文件:{}",appendixFiles.get(0).getFileUrl());
                log.info("下载单个文件路径:{}",appendixFiles.get(0).getFileUrl());
                uploadAppendixFileService.downloadAppendixFileSingle(request,resp,appendixFiles.get(0),Constants.NumberStr.NUM_STR_TWO);
            }
        }
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - 发布
     * @param request request
     * @param id id
     * @return Result
     */
    @Log(type = "更新", value = "发布公告")
    @RequestMapping("/azbj/tzgggl/noticeInfoManage/announce/{id}")
    public Result announce(HttpServletRequest request,@PathVariable String id) {
        int num = noticeInfoManageService.announce(id);
        if(Constants.Number.NUM_ZERO < num) {
            return Result.success("发布成功");
        } else {
            return Result.failure(ReturnCode.FAILURE);
        }
    }

    /**
     * 安帮工作资源管理 - 通知公告信息管理 - 通知公告信息管理 - 取消发布
     * @param request request
     * @param id id
     * @return Result
     */
    @Log(type = "更新", value = "取消发布公告")
    @RequestMapping("/azbj/tzgggl/noticeInfoManage/withdraw/{id}")
    public Result withdraw(HttpServletRequest request,@PathVariable String id) {
        int num = noticeInfoManageService.withdraw(id);
        if(Constants.Number.NUM_ZERO < num) {
            return Result.success("撤回成功");
        } else {
            return Result.failure(ReturnCode.FAILURE);
        }
    }
}